import DatePicker from "components/antd-compatible/date-picker";
/**
 * Created by tanbingqin on 2020/7/20.
 */
import React, { Component, PropTypes } from "react";
import { messages, deepFullCopy, eventTrack } from 'share/common'
import { connect } from 'react-redux';
import moment from 'moment'
import config from 'config'
import travelService from 'containers/request/travel-request/travel.service'
import errorMessage from 'share/errorMessage';
import 'styles/request/new-card-request.scss'
import { Button, Row, Col, Icon,  Checkbox, message, Popconfirm, Spin, Divider, Switch } from 'antd'
const { RangePicker } = DatePicker;
import Condition from 'components/condition';
const If = Condition.If;
import travelUtil from 'containers/request/travel-request/travelUtil'
import requestUtil from 'containers/request/slide/request-util'
const CheckboxGroup = Checkbox.Group;
import Chooser from 'components/chooser'
import chooserData from 'share/chooserData'

class RequestItinerarySubsidy extends Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      subsidyConfig: {},
    };
  }

  componentDidMount() {
    const { subsidyConfig } = this.props.params;

    let subsidy = JSON.parse(JSON.stringify(subsidyConfig));
    subsidy.itineraryHeadPropertyDTOs && subsidy.itineraryHeadPropertyDTOs.forEach(itinerary => {
      itinerary.subsidyStartDate = itinerary.startDate;
      itinerary.subsidyEndDate = itinerary.endDate;
    });
    this.setState({subsidyConfig: subsidy}, this.initExpenseTypeList);
  }

  componentWillReceiveProps(nextProps) {}

  initExpenseTypeList = () => {
    let { subsidyConfig } = this.state;

    //判断是否配置了行程值列表，如果配置了，则无需初始化计算差补费用类型
    if (requestUtil.isHasCustList(subsidyConfig)) {
      return;
    }
    subsidyConfig.itineraryHeadPropertyDTOs && subsidyConfig.itineraryHeadPropertyDTOs.forEach(itinerary => {
      this.getSubsidyType(itinerary, subsidyConfig);
    });
  };

  //获取差补可选费用类型
  getSubsidyType = (itinerary, subsidyConfig) => {
    let params = {
      applicationOID: itinerary.applicationOID,
      cityCode: itinerary.toCityCode,
      cityName: itinerary.toCityName
    };
    let custList = itinerary.travelSubsidiesRequestDTO && itinerary.travelSubsidiesRequestDTO.travelSubsidiesCustListDTOs;
    if (custList) {
      params.travelSubsidiesCustListDTOs = [];
      custList.forEach(cust => {
        params.travelSubsidiesCustListDTOs.push({
          custEnumerationOID: cust.custEnumerationOID,
          value: cust.value
        });
      });
    }
    itinerary.loading = true;
    this.setState({subsidyConfig});
    travelService.requestSubsidyType(params).then(res => {
      itinerary.loading = false;
      if (res.data) {
        itinerary.id = res.data.id; //差补行程id
        itinerary.expenseTypes = res.data.expenseTypes || []; //差补行程可见费用类型
        itinerary.expenseTypeOIDs = [];
        if (subsidyConfig.subsidySelection) {
          itinerary.expenseTypes.forEach(item => {
            if (item.selectFlag) {
              itinerary.expenseTypeOIDs.push(item.expenseTypeOID);
            }
          }); //差补选中的费用类型
        }
      }
      this.setState({subsidyConfig});
    }).catch(e => {
      errorMessage(e.response);
      itinerary.loading = false;
      this.setState({subsidyConfig});
    });
  };

  onCancel = () => {
    this.props.close();
  };

  handleStatusChange = (value, itineraryIndex) => {
    eventTrack({
      category: '计算补贴',
      action: '计算开关'
    });
    let { subsidyConfig } = this.state;
    subsidyConfig.itineraryHeadPropertyDTOs[itineraryIndex].isIgnore = !value;
    this.setState({subsidyConfig});
  };

  handleCustChange = (value, allItem, custEnumerationOID, itineraryIndex) => {
    let { subsidyConfig } = this.state;
    let itinerary = subsidyConfig.itineraryHeadPropertyDTOs[itineraryIndex];
    let custList = itinerary.travelSubsidiesRequestDTO && itinerary.travelSubsidiesRequestDTO.travelSubsidiesCustListDTOs;
    let isHasChange = false;
    custList.forEach(cust => {
      if (cust.custEnumerationOID === custEnumerationOID && cust.value !== value) {
        isHasChange = true;
        cust.value = value;
        cust.showValue = allItem ? allItem.messageKey : '';
      }
    });
    //chooser第一次进来会触发onchange，实际没有change
    if (isHasChange) {
      this.setState({subsidyConfig}, () => {
        if (requestUtil.judgeIsAllHaveValue(this.state.subsidyConfig, itineraryIndex)) {
          let itinerary = this.state.subsidyConfig.itineraryHeadPropertyDTOs[itineraryIndex];
          this.getSubsidyType(itinerary, this.state.subsidyConfig);
        }
      });
    }
  };

  refreshSubsidy = (itineraryIndex) => {
    eventTrack({
      category: '计算补贴',
      action: '刷新补贴按钮'
    });
    let { subsidyConfig } = this.state;
    let itinerary = subsidyConfig.itineraryHeadPropertyDTOs[itineraryIndex];
    this.getSubsidyType(itinerary, subsidyConfig);
  };

  handleExpenseChange = (value, itineraryIndex) => {
    let { subsidyConfig } = this.state;
    let itinerary = subsidyConfig.itineraryHeadPropertyDTOs[itineraryIndex];
    itinerary.expenseTypeOIDs = value;
    this.setState({subsidyConfig});
  };

  toggleAllSubsidyType = (value, itineraryIndex) => {
    if (value) {
      eventTrack({
        category: '计算补贴',
        action: '全选勾选'
      });
    } else {
      eventTrack({
        category: '计算补贴',
        action: '全选取消勾选'
      });
    }
    let { subsidyConfig } = this.state;
    let itinerary = subsidyConfig.itineraryHeadPropertyDTOs[itineraryIndex];
    itinerary.expenseTypeOIDs = value ? itinerary.expenseTypes.map(item => item.expenseTypeOID) : [];
    this.setState({subsidyConfig});
  };

  handleChangeDate = (dates, dateStrings, itineraryIndex) => {
    let { subsidyConfig } = this.state;
    let itinerary = subsidyConfig.itineraryHeadPropertyDTOs[itineraryIndex];
    if (dateStrings && dateStrings.length === 2) {
      itinerary.subsidyStartDate = moment(dateStrings[0]).hours(0).minutes(0).seconds(0).utc().format();
      itinerary.subsidyEndDate = moment(dateStrings[1]).hours(0).minutes(0).seconds(0).utc().format();
    }
    this.setState({subsidyConfig});
  };

  handleSave = () => {
    const { close } = this.props;
    const { subsidyConfig } = this.state;
    let length = subsidyConfig.itineraryHeadPropertyDTOs.length;
    let i = 0;
    for (i; i < length; i++) {
      let itinerary = subsidyConfig.itineraryHeadPropertyDTOs[i];
      if (!itinerary.isIgnore) {
        if (!requestUtil.judgeIsAllHaveValue(subsidyConfig, i)) {
          message.error(messages('request-1.key399',{arg1: i+1})/*行程{arg1}有未填的必填项*/);
          return;
        }
        if (!itinerary.expenseTypeOIDs || !itinerary.expenseTypeOIDs.length) {
          message.error(messages('request-1.key400',{arg1: i+1})/*请选择行程{arg1}的补贴类型*/);
          return;
        }
      }
    }

    //封装成生成明细需要的数据
    let postData = [];
    subsidyConfig.itineraryHeadPropertyDTOs.forEach(itinerary => {
      if (!itinerary.isIgnore) {
        let item = {
          id: itinerary.id,
          itineraryHeadId: itinerary.itineraryHeadId,
          applicationOID: itinerary.applicationOID,
          startDate: itinerary.subsidyStartDate,
          endDate: itinerary.subsidyEndDate,
          cityCode: itinerary.toCityCode,
          cityName: itinerary.toCityName,
          expenseTypeOIDs: itinerary.expenseTypeOIDs
        };
        let custList = itinerary.travelSubsidiesRequestDTO && itinerary.travelSubsidiesRequestDTO.travelSubsidiesCustListDTOs;
        if (custList && custList.length) {
          item.travelSubsidiesCustListDTOs = [];
          custList.forEach(cust => {
            item.travelSubsidiesCustListDTOs.push({
              custEnumerationOID: cust.custEnumerationOID,
              value: cust.value
            });
          });
        }
        postData.push(item);
      }
    });
    close(postData);
  };

  render() {
    const { subsidyConfig } = this.state;
    return (
      <div className="itinerary-subsidy">
        <div>
          {subsidyConfig.itineraryHeadPropertyDTOs && subsidyConfig.itineraryHeadPropertyDTOs.map((itinerary, itineraryIndex) => {
            let custList = itinerary.travelSubsidiesRequestDTO && itinerary.travelSubsidiesRequestDTO.travelSubsidiesCustListDTOs;
            return (
              <div key={itinerary.itineraryHeadId} className="itinerary-subsidy-block">
                <div className="itinerary-item-title">
                  <div className="font-no">{messages('request-1.key290')/*行程*/}{itineraryIndex + 1}</div>
                  <Row type="flex" align="middle">
                    <Col span={20}>
                      <span className="font-title">{itinerary.fromCityName}&nbsp;-&nbsp;{itinerary.toCityName}</span>
                      <span className="font-sub">
                        {moment(itinerary.startDate).format('YYYY-MM-DD')}
                        &nbsp;~&nbsp;
                        {moment(itinerary.endDate).format('YYYY-MM-DD')}，
                        {messages('request-1.key384',{arg1: travelUtil.calculateDate(itinerary.startDate,itinerary.endDate)})/*共{arg1}天*/}
                      </span>
                    </Col>
                    <Col span={4} style={{textAlign: 'right'}}>
                      {itinerary.isIgnore ? messages('request-1.key401')/*不计算*/ : messages('request-1.key402')/*计算*/}&nbsp;&nbsp;
                      <Switch
                        size="small"
                        checked={!itinerary.isIgnore}
                        onChange={value => this.handleStatusChange(value, itineraryIndex)}
                      />
                    </Col>
                  </Row>
                </div>
                <div className={`itinerary-subsidy-content ${itinerary.isIgnore ? 'removed' : ''}`}>
                  <If value={subsidyConfig.subsidiesDateEditable}>
                    <Row type="flex" align="middle" className="margin-bottom-12">
                      <Col span={4}>
                        {messages('request-1.key403')/*补贴日期*/}<span className="span-required">*</span>
                      </Col>
                      <Col span={16} offset={1}>
                        <RangePicker
                          allowClear={false}
                          getCalendarContainer={triggerNode => triggerNode.parentNode}
                          format="YYYY-MM-DD"
                          placeholder={[messages('request-1.key396')/*开始日期*/, messages('common.end.date')/*结束日期*/]}
                          value={[moment(itinerary.subsidyStartDate), moment(itinerary.subsidyEndDate)]}
                          onChange={(dates, dateStrings) => this.handleChangeDate(dates, dateStrings, itineraryIndex)}
                          style={{width: '100%'}}
                          disabledDate={current => requestUtil.disabledDateByParam(current, itinerary.startDate, itinerary.endDate, true)}
                        />
                      </Col>
                    </Row>
                  </If>
                  <If value={custList && custList.length}>
                    {custList && custList.map(cust => {
                      let selectorItem = deepFullCopy(chooserData['multi_cust_list']);
                      selectorItem.title = messages('request-1.key404')/*自定义列表*/;
                      selectorItem.url = `${config.baseUrl}/api/custom/enumerations/${cust.custEnumerationOID}/items/v2`;
                      return (
                        <Row type="flex" align="middle" className="margin-bottom-12">
                          <Col span={4}>
                            {cust.custEnumerationName}<span className="span-required">*</span>
                          </Col>
                          <Col span={16} offset={1}>
                            <Chooser
                              selectorItem={selectorItem}
                              placeholder={messages('common.select')/*请选择*/}
                              valueKey="value"
                              labelKey="messageKey"
                              onlyNeed="value"
                              value={cust.value ? [{messageKey: cust.showValue, value: cust.value}] : undefined}
                              onChange={(value, allItem) => this.handleCustChange(value, allItem, cust.custEnumerationOID, itineraryIndex)}
                              single
                            />
                          </Col>
                        </Row>
                      )
                    })}
                  </If>
                  <Row type="flex" align="top" className="expense-row">
                    <Col span={4}>
                      {messages('request-1.key405')/*补贴类型*/}<span className="span-required">*</span>
                    </Col>
                    <Col span={16} offset={1}>
                      <If value={requestUtil.judgeIsAllHaveValue(subsidyConfig, itineraryIndex)}>
                        <If value={itinerary.expenseTypes && itinerary.expenseTypes.length}>
                          <Row>
                            <Checkbox
                              value="ALL"
                              checked={requestUtil.isSelectAll(itinerary)}
                              onClick={(e)=>this.toggleAllSubsidyType(e.target.checked, itineraryIndex)}
                            >
                              {messages('request-1.key406')/*全选*/}
                            </Checkbox>
                            <CheckboxGroup
                              value={itinerary.expenseTypeOIDs || []}
                              onChange={value => this.handleExpenseChange(value, itineraryIndex)}
                            >
                              {itinerary.expenseTypes && itinerary.expenseTypes.map(expense => {
                                return (
                                  <Checkbox value={expense.expenseTypeOID}>{expense.name}</Checkbox>
                                )
                              })}
                            </CheckboxGroup>
                          </Row>
                        </If>
                        <If value={!(itinerary.expenseTypes && itinerary.expenseTypes.length) && !itinerary.loading}>
                          <span className="span-error">{messages('request-1.key407')/*无匹配补贴类型*/}</span>
                        </If>
                        <If value={!itinerary.loading}>
                          <div>
                            <span className="icon-btn" onClick={() => this.refreshSubsidy(itineraryIndex)}>
                              <Icon type="sync" />&nbsp;&nbsp;{messages('request-1.key408')/*刷新补贴类型*/}
                            </span>
                          </div>
                        </If>
                      </If>
                      <If value={!!itinerary.loading}>
                        <Icon type="loading" />&nbsp;&nbsp;
                        <span className="span-desc" style={{fontSize: '12px'}}>{messages('request-1.key409')/*正在查询补贴类型...*/}</span>
                      </If>
                      <If value={!requestUtil.judgeIsAllHaveValue(subsidyConfig, itineraryIndex) && !itinerary.loading}>
                        <span className="span-desc">{messages('request-1.key410')/*输入必填条件后，将自动为您计算补贴类型*/}</span>
                      </If>
                    </Col>
                  </Row>
                </div>
              </div>
            )
          })}
        </div>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave}>{messages('common.ok')/*确定*/}</Button>
          <Button onClick={this.onCancel}>{messages('common.cancel')/*取消*/}</Button>
        </div>
      </div>
    )
  }
}

RequestItinerarySubsidy.propTypes = {

};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    newProfile: state.login.options
  }
}

export default connect(mapStateToProps)(RequestItinerarySubsidy);
